<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/9/4
 * Time: 17:18
 */

declare (strict_types=1);

namespace app\service\traits;


trait SingleCase
{
    /** @var array */
    private static $instance = [];

    // 传入数据
    protected $data;

    // 禁止克隆
    private function __clone()
    {
    }

    /**
     * 私有构造
     *
     * SingleCase constructor.
     * @param array $data
     */
    private function __construct(array $data)
    {
        $this->data = $data;

        // 初始化方法
        $this->init();
    }

    /**
     * init 方法
     */
    protected function init()
    {
    }

    /**
     * 获取实例
     *
     * @param array $data
     * @param bool $isNew
     * @return static
     */
    static public function getInstance(array $data = [], bool $isNew = false)
    {
        $class = get_called_class();

        if (!array_key_exists($class, self::$instance) || $isNew) {
            $instance = new static($data);

            self::$instance[$class] = $instance;
        }

        return self::$instance[$class];
    }
}
